package com.ben.multiple.util;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import java.util.UUID;

/**
 * 随机数工具
 *
 * @author BenJin Yin
 * @date 2019/10/24
 */
public final class RandomUtils {
    private static final String LOCAL_DATE_TIME_PATTERN = "yyMMddHHmmss";
    private static final String SUPPLY_CHAR = "0";

    /**
     * 生成 16位唯一编号，12位时间，2位随机数，2位 id；能应付 1000/s ；如果要应付高并发，可以加上秒后的时间值
     *
     * @param id 唯一标识
     * @return 16位
     */
    public static String get16BitUniqueNo(Integer id) {
        Random random = new Random();
        id = id == null ? random.nextInt(100) : id;
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern(LOCAL_DATE_TIME_PATTERN));
        String idStr = String.valueOf(id < 0 ? -id : id);
        if (idStr.length() == 1) {
            idStr = SUPPLY_CHAR + idStr;
        } else {
            idStr = idStr.substring(idStr.length() - 2);
        }
        return time + random.nextInt(10) + random.nextInt(10) + idStr;
    }

    /**
     * 15位时间，2位随机数，3位 id；能应付 100000/s
     *
     * @param id 唯一标识
     * @return 20位
     */
    public static String get20BitUniqueNo(Integer id) {
        Random random = new Random();
        LocalDateTime localDateTime = LocalDateTime.now();
        String nanoStr = String.valueOf(localDateTime.getNano());
        if (nanoStr.length() == 1) {
            nanoStr = SUPPLY_CHAR + SUPPLY_CHAR + nanoStr;
        } else if (nanoStr.length() == 2) {
            nanoStr = SUPPLY_CHAR + nanoStr;
        } else {
            nanoStr = nanoStr.substring(0, 3);
        }
        String time = localDateTime.format(DateTimeFormatter.ofPattern(LOCAL_DATE_TIME_PATTERN)) + nanoStr;
        id = id == null ? random.nextInt(1000) : id;
        String idStr = String.valueOf(id < 0 ? -id : id);
        if (idStr.length() == 1) {
            idStr = SUPPLY_CHAR + SUPPLY_CHAR + idStr;
        } else if (idStr.length() == 2) {
            idStr = SUPPLY_CHAR + idStr;
        } else {
            idStr = idStr.substring(idStr.length() - 3);
        }
        return time + random.nextInt(10) + random.nextInt(10) + idStr;
    }

    /**
     * 生成 32 位唯一编码
     *
     * @return String
     */
    public static String getuuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

}
